package com.agriculture.controller;

import com.agriculture.common.Response;
import com.agriculture.domain.User;
import com.agriculture.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/users")
    public Response<?> getUsers(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String role,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            return adminService.getUsers(keyword, role, page, pageSize);
        } catch (Exception e) {
            return Response.error("获取用户列表失败: " + e.getMessage());
        }
    }

    @PutMapping("/users/{userId}/status")
    public Response<?> updateUserStatus(
            @PathVariable Long userId,
            @RequestBody Map<String, String> statusMap) {
        try {
            String status = statusMap.get("status");
            return adminService.updateUserStatus(userId, status);
        } catch (Exception e) {
            return Response.error("更新用户状态失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/users/{userId}")
    public Response<?> deleteUser(@PathVariable Long userId) {
        try {
            return adminService.deleteUser(userId);
        } catch (Exception e) {
            return Response.error("删除用户失败: " + e.getMessage());
        }
    }

    @GetMapping("/users/{userId}")
    public Response<?> getUser(@PathVariable Long userId) {
        try {
            return adminService.getUserById(userId);
        } catch (Exception e) {
            return Response.error("获取用户信息失败: " + e.getMessage());
        }
    }

    @PutMapping("/users/{userId}")
    public Response<?> updateUser(
            @PathVariable Long userId,
            @RequestBody Map<String, String> userData) {
        try {
            User user = adminService.getUser(userId);
            if (user == null) {
                return Response.error("用户不存在");
            }
            
            // 设置要更新的字段
            user.setUserId(userId);  // 确保设置userId
            user.setPhoneNumber(userData.get("phoneNumber"));
            user.setEmail(userData.get("email"));
            user.setAddress(userData.get("address"));
            
            adminService.updateUser(user);
            return Response.success("更新用户信息成功", user);
        } catch (Exception e) {
            return Response.error("更新用户信息失败: " + e.getMessage());
        }
    }
} 